package com.ruoze.bdp.controller;

import com.ruoze.bdp.commons.ResponseDto;
import com.ruoze.bdp.entity.ClusterEntity;
import com.ruoze.bdp.entity.ClusterVo;
import com.ruoze.bdp.entity.cluster.ClusterRequest;
import com.ruoze.bdp.enums.ExceptionEnum;
import com.ruoze.bdp.service.ClusterService;
import com.ruoze.bdp.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RequestMapping("/cluster")
@RestController
public class ClusterController {
    @Autowired
    private ClusterService clusterService;

    @GetMapping("/list")
    public ResponseDto<Page<ClusterEntity>> queryPage(@RequestParam(required = false) String name,
                                                      @RequestParam(defaultValue = "1") int pageNum,
                                                      @RequestParam(defaultValue = "10") int pageSize) {
        ClusterRequest clusterRequest = new ClusterRequest(name, pageNum, pageSize);
        Page<ClusterEntity> pageDto = clusterService.queryPage(clusterRequest);
        return ResponseUtil.successData(pageDto);
    }



    @PostMapping("/add")
    public ResponseDto createNewCluster(@RequestBody ClusterVo newCluster) {
        clusterService.createNewCluster(newCluster);
        return ResponseUtil.successData(ExceptionEnum.ADD_SUCCESS.getCode(),ExceptionEnum.ADD_SUCCESS.getMsg());
    }

    @PutMapping("/edit/{id}")
    public ResponseDto replaceNewDataSource(@RequestBody ClusterVo newCluster, @PathVariable long id) {
        clusterService.replaceNewCluster(newCluster, id);
        return ResponseUtil.successData(ExceptionEnum.EDIT_SUCCESS.getCode(),ExceptionEnum.EDIT_SUCCESS.getMsg());
    }

    @DeleteMapping("/delete/{id}")
    public ResponseDto deleteSingleDataSource(@PathVariable long id) {
        clusterService.logicalDelCluster(id);
        return ResponseUtil.successData(ExceptionEnum.DELETE_SUCCESS.getCode(),ExceptionEnum.DELETE_SUCCESS.getMsg());
    }

    @DeleteMapping("/delete/batch")
    public ResponseDto deleteBatchDataSource(@RequestParam String ids) {
        List<Long> idList = new ArrayList<>();
        for (String id : ids.split(",")) {
            idList.add(Long.parseLong(id));
        }
        clusterService.logicalBatchDelCluster(idList);
        return ResponseUtil.successData(ExceptionEnum.DELETE_SUCCESS.getCode(),ExceptionEnum.DELETE_SUCCESS.getMsg());
    }

    @GetMapping("/all")
    public ResponseDto<List<ClusterEntity>> queryAll() {
        // 给前端提供查询所有集群的接口
        List<ClusterEntity> clusterEntityList = clusterService.queryAll();
        return ResponseUtil.successData(clusterEntityList);
    }
}
